package com.zxs.service;

import com.zxs.annotation.DingTalkBack;
import com.zxs.annotation.DingTalkColumn;
import com.zxs.annotation.DingTalkFix;
import com.zxs.service.impl.IZServiceImpl;
import com.zxs.util.ZspecUitl;
import jakarta.annotation.Resource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Service
public class ZxsDingTalkService extends IZServiceImpl implements DingTalkService {


    @Override
    public String executeSend(ProceedingJoinPoint joinPoint) throws IOException {
        Method method = ZspecUitl.getSpecificmethod(joinPoint);
        // 获取注解
        DingTalkFix dingTalkFix = AnnotationUtils.findAnnotation(method, DingTalkFix.class);
        var message = assemble(dingTalkFix.mdName());
        return pushText(message);
    }

    @Override
    public void executeSendBack(JoinPoint joinPoint, Object returnDto) throws Exception {
        Method method = ZspecUitl.getSpecificmethod(joinPoint);
        Class <?> zxsClass = method.getReturnType();
        DingTalkBack dingTalkBack = AnnotationUtils.findAnnotation(method, DingTalkBack.class);
        var message = assemble(dingTalkBack.mdName(),returnDto,zxsClass);
        pushText(message);
    }

    private String assemble(String mdName) throws IOException {
        String content =readFile(mdName);
        return content;
    }

    private String assemble(String mdName,Object returnDto, Class<?> zxsClass) throws Exception {
        System.out.println(zxsClass.getName());
        Field[] fields = zxsClass.getDeclaredFields();
        String content =readFile(mdName);
        for (Field field : fields) {
            if (field.isAnnotationPresent(DingTalkColumn.class)) {
                String fieldName=field.getName();
                String	methodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                Method methods = zxsClass.getMethod(methodName);
                Object object =  methods.invoke(returnDto);
                DingTalkColumn annotation = field.getAnnotation(DingTalkColumn.class);
                content = content.replaceAll(annotation.field(),object.toString());
            }
        }
        return content;
    }
}
